/*************************************************************************
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *
 *                COPYRIGHT (C) HONGLING CAPITAL CORPORATION 2012
 *    ALL RIGHTS RESERVED BY HONGLING CAPITAL CORPORATION. THIS PROGRAM
 * MUST BE USED  SOLELY FOR THE PURPOSE FOR WHICH IT WAS FURNISHED BY
 * HONGLING CAPITAL CORPORATION. NO PART OF THIS PROGRAM MAY BE REPRODUCED
 * OR DISCLOSED TO OTHERS,IN ANY FORM, WITHOUT THE PRIOR WRITTEN
 * PERMISSION OF HONGLING CAPITAL CORPORATION. USE OF COPYRIGHT NOTICE
 DOES NOT EVIDENCE PUBLICATION OF THE PROGRAM.
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *************************************************************************/

package com.springboot.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 404异常以及个别特殊网络异常捕获。
 *
 * @author hongchao zhao at 2019-4-24 15:47
 */
@Controller
public class NotFoundException implements ErrorController {

    private static Logger LOG = LoggerFactory.getLogger(NotFoundException.class);

    /**
     * 定义全局错误捕获页面。
     */
    public static final String DEFAULT_ERROR_VIEW = "html/error/404";

    @Override
    public String getErrorPath() {
        return "/error";
    }


    /**
     * 网站请求错误捕获。
     *
     * @param req
     * @return
     */
    @RequestMapping(value = {"/error"})
    public ModelAndView error(HttpServletRequest req) {
        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
        LOG.debug("【错误捕获】当前请求地址【{}】，请求异常码【{}】。。", req.getRequestURL(),statusCode);
        String message = "";
        if(statusCode == 400){
            message = "请求出错，由于语法格式有误，服务器无法理解此请求。";
        }else if(statusCode == 401){
            message = "未授权，请与 Web 服务器的管理员联系，以确认您是否具有访问所请求资源的权限。 ";
        }else if(statusCode == 403){
            message = "禁止访问，如果问题依然存在，请与 Web服务器的管理员联系。";
        }else if(statusCode == 404){
            message = "不好意思，您访问的页面不存在~ ";
        }else{
            message = "服务器的内部错误，Web 服务器不能执行此请求。请稍后重试此请求。 ";
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("url", req.getRequestURL());
        mav.addObject("code", statusCode);
        mav.addObject("message", message);
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }


}
